package com.tgh.au.c5;

import java.util.concurrent.TimeUnit;
import com.tgh.au.R;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.view.MotionEvent;
import android.view.View;

public class GameView9 extends View implements Runnable {
	int backWidth;
	int backHeight;
	short[] buf1;
	short[] buf2;
	int[] bitmap1;
	int[] bitmap2;
	
	
	public GameView9(Context context) {
		super(context);
		setFocusable(true);
		requestFocus();
		Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.qq);
		backWidth=bitmap.getWidth();
		backHeight=bitmap.getHeight();
		buf1=new short[backWidth*backHeight];
		buf2=new short[backWidth*backHeight];
		bitmap1=new int[backWidth*backHeight];
		bitmap2=new int[backWidth*backHeight];
		//加载图像的像素到数组中
		bitmap.getPixels(bitmap1, 0, backWidth, 0, 0, backWidth, backHeight);
		new Thread(this).start();
	}
	/**
	 * 仍石头
	 * @param x x坐标
	 * @param y y坐标
	 * @param stoneSize 波源半径
	 * @param stoneWeight 波源能量
	 */
	void dropStone(int x,int y,int stoneSize,int stoneWeight){
		for (int posX = x-stoneSize; posX < x+stoneSize; posX++) {
			for (int posY = y-stoneSize; posY < y+stoneSize; posY++) {
				if ((posX-x)*(posX-x)+(posY-y)*(posY-y)<stoneSize*stoneSize) {
					buf1[backWidth*posY+posX]=(short) -stoneWeight;
				}
			}
		}
	}
	@Override
	public boolean onTouchEvent(MotionEvent event) {
		dropStone(backWidth/2, backHeight/2, 60,300);
		return true;
	}
	/**
	 * 波纹扩散
	 */
	void rippleSpread(){
		for (int i = backWidth; i < backWidth*backHeight-backWidth; i++) {
			buf2[i]=(short) ((buf1[i-1]+buf1[i+1]+buf1[i-backWidth]+buf1[i+backWidth])>>1-buf2[i]);
			//波能衰减
			buf2[i]-=buf2[i]>>5;
		}
	}
	/**
	 * 渲染水纹效果
	 */
	void render(){
		int xoff,yoff;
		int k=backWidth;
		for (int i = 1; i <backHeight-1; i++) {
			for (int j = 0; j < backWidth; j++) {
				xoff=buf1[k-1]-buf1[k+1];
				yoff=buf1[k-backWidth]-buf1[k+backWidth];
				//判断是否在窗口的范围内
				if ((i+yoff)<0) {
					k++;
					continue;
				}
				if ((i+yoff)>backHeight) {
					k++;
					continue;
				}
				if ((j+xoff)<0) {
					k++;
					continue;
				}
				if ((j+xoff)>backWidth) {
					k++;
					continue;
				}
				//计算出偏移像素和原始像素的内存地址偏移量
				int pos1,pos2;
				pos1=backWidth*(i+yoff)+(j+xoff);
				pos2=backWidth*i+j;
				bitmap2[pos2++]=bitmap1[pos1++];
				k++;
			}
		}
	}
	@Override
	protected void onDraw(Canvas canvas) {
		canvas.drawBitmap(bitmap2, 0, backWidth, 0, 0, backWidth, backHeight, false, null);
	}
	@Override
	public void run() {
		while (!Thread.currentThread().isInterrupted()) {
			try {
				TimeUnit.MILLISECONDS.sleep(100);
			} catch (InterruptedException e) {
				Thread.currentThread().interrupt();
			}
			rippleSpread();
			render();
			postInvalidate();
		}
	}
}
